package com.jwd.launch.service;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class BTSwitcherService extends Service {

    private static final String TAG = "JK_AnywheeBt_BTSwitcherService";
    private BluetoothAdapter mBluetoothAdapter;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.v(TAG, "BTSwitcherService onCreate");
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "BTSwitcherService onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        Log.e(TAG, "BTSwitcherService onBind");
        return mService;
    }

    @Override
    public void onDestroy() {
        Log.v(TAG, "IBTSwitcherService onDestroy");
    }

    IBTSwitcherService.Stub mService = new IBTSwitcherService.Stub() {
        @Override
        public int open() throws RemoteException {
            Log.e(TAG, "open BT");
            boolean bState = mBluetoothAdapter.isEnabled();
            if(!bState) {
                try {
                    if(mBluetoothAdapter.enable()) {
                        return 1;
                    } else {
                        return -1;
                    }
                } catch(Exception e) {
                    e.printStackTrace();
                }
            } else {
                return 1;
            }
            return 0;
        }

        @Override
        public int close() throws RemoteException {
            Log.e(TAG, "close BT");
            boolean bState = mBluetoothAdapter.isEnabled();
            if(bState) {
                try {
                    if(mBluetoothAdapter.disable()) {
                        return 1;
                    } else {
                        return -1;
                    }
                } catch(Exception e) {
                    e.printStackTrace();
                }
            } else {
                return 1;
            }
            return 0;
        }
    };
}
